// Created by Xslt generator for Eclipse.
// XSL :  not found (java.io.FileNotFoundException:  (Bad file descriptor))
// Default XSL used : easystruts.jar$org.easystruts.xslgen.JavaClass.xsl

package com.ba360.struts.action;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Properties;

import javax.naming.Context;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.sql.DataSource;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.ba360.portal.common.PortalConstants;
import com.ba360.portal.database.DBConnectionImpl;
import com.ba360.portal.database.dbo.User;
import com.ba360.portal.database.dbo.User_23Feb09;
import com.ba360.portal.util.EmailSender;
import com.ba360.portal.util.Log;
import com.ba360.struts.form.RegistrationForm;
import com.ba360.struts.form.RegistrationForm_23Feb09;
/**
 * RegistrationFormAction.java created by EasyStruts - XsltGen.
 * http://easystruts.sf.net created on 04-01-2004
 * 
 * XDoclet definition:
 * 
 * @struts:action path="/" name="RegistrationForm"
 *                input="/jsp/UserRegistration.jsp" validate="true"
 * @struts:action-forward name="/jsp/Login.jsp" path="/jsp/Login.jsp"
 * @struts:action-forward name="/jsp/UserRegistration.jsp"
 *                        path="/jsp/UserRegistration.jsp"
 */
public class RegistrationFormAction_23Feb09 extends Action {

	// --------------------------------------------------------- Instance
	// Variables

	// --------------------------------------------------------- Methods

	/**
	 * Method execute
	 * 
	 * @param ActionMapping
	 *            mapping
	 * @param ActionForm
	 *            form
	 * @param HttpServletRequest
	 *            request
	 * @param HttpServletResponse
	 *            response
	 * @return ActionForward
	 * @throws Exception
	 */
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		// RegistrationForm registrationForm = (RegistrationForm) form; Modified by Arun 09-MAY-2009
		RegistrationForm_23Feb09 registrationForm = (RegistrationForm_23Feb09)form;
		Log.init(this.getClass());
		if (registrationForm == null) {
			return mapping.findForward("faliure");
		}

		String value = "";
		String bDay = registrationForm.getBirthdayYear() + "-"
				+ registrationForm.getBirthdayMonth() + "-"
				+ registrationForm.getBirthDayDate();
		String tel = registrationForm.getTelephone();
		String gender = registrationForm.getGender();
		String zip = registrationForm.getZip();
		String fn = registrationForm.getFirstName();
		String ln = registrationForm.getLastName();
		String email = registrationForm.getEmail();
		String city = registrationForm.getCity();
		String state = registrationForm.getState();
		String country = registrationForm.getCountry();
		String address = registrationForm.getAddress();
		Context context = null;
		DataSource ds = null;
		Connection conn = null;
		Statement stmt = null;
		DBConnectionImpl dbConn = new DBConnectionImpl();
		conn = dbConn.getConnection();
		String action = request.getParameter(PortalConstants.ACTION);
		HttpSession session = request.getSession();
		if (action == null) {
			return mapping.findForward("failure");
		}

		//throw new UnsupportedOperationException("Generated method
		// 'execute(...)' not implemented.");
		if (action.equals("Save")) {
			session.removeAttribute("NEWUSER");

			try {

				//Class.forName("org.gjt.mm.mysql.Driver");
				//Connection con
				// =DriverManager.getConnection("jdbc:mysql://localhost:3306/classifiedsdb","portal","p0rtal");
				stmt = conn.createStatement();
				ResultSet rs = stmt
						.executeQuery("select count(*) from userinfo where emailaddress='"
								+ registrationForm.getEmail() + "'");
				rs.next();
				int count = Integer.parseInt(rs.getString(1));
				session.removeAttribute("USER_EXIST");
				Log.info("User Exist: " + count);
				if (count > 0) {
					Log.info("Found User Match " + registrationForm.getEmail());
					//		HttpSession session = request.getSession();
					//mapping.setParameter("ErrorType");
					session.setAttribute("USER_EXIST", registrationForm
							.getEmail());
					return mapping.findForward("failure");
				}
				if(zip == null)
					zip = "0";
				String insStatement = "INSERT INTO userinfo "
						+ "(birthday,telephone,gender,zip,firstname,lastname,emailaddress,city,state,country,address,date_created) VALUES(";
				value = "'" + bDay + "','" + tel + "','" + gender + "','" + zip
						+ "','" + fn + "','" + ln + "','" + email + "','"
						+ city + "','" + state + "','" + country + "','"
						+ address + "',NOW()"+")";
				Log.info(insStatement + value);
				stmt.execute(insStatement + value);

				//conn.commit();
				ResultSet rs1 = stmt
						.executeQuery("select userid from userinfo where emailaddress='"
								+ registrationForm.getEmail() + "'");
				rs1.next();
				String userid = rs1.getString(1);
				Log.info("New UserID:" + userid);
				rs1.close();
				stmt.execute("insert into userauth(userid,password) values('"
						+ userid + "','" + registrationForm.getPassword()
						+ "')");
				//conn.commit();
				session.setAttribute("NEWUSER", "NEWUSER");
				Log.info(" Registration successfull for user: "
						+ registrationForm.getEmail());
				
				Properties prop = new Properties();
				prop.setProperty("FullName", registrationForm.getFirstName()+" "+registrationForm.getLastName());
				prop.setProperty("EmailAddr",registrationForm.getEmail() );
				prop.setProperty("Password", registrationForm.getPassword());
				try{
					EmailSender.sendEmail(EmailSender.TYPE_REGISTRATION,prop);
				}catch (Exception e)
				{
					Log.error(e.getMessage());
				}
				Log.info(" Send email to: "
						+ registrationForm.getEmail());
			conn.close();
			} catch (Exception e) {
				Log.error(e.getMessage());
				e.printStackTrace();

				return mapping.findForward("failure");
			}finally{
				conn.close();
			}

			return mapping.findForward("success");

		} else if (action.equals("UpdateInfo")) {
			try {

				//User user = (User) session.getAttribute(PortalConstants.USER); Modified by Arun on 10-MAY-2009
				User_23Feb09 user = (User_23Feb09) session.getAttribute(PortalConstants.USER); 
				
				String updateStmt = "update userinfo set ";
				value = User_23Feb09.USER_BDAY + "='" + bDay + "'," + User_23Feb09.USER_TEL
						+ "=" + "'" + tel + "'," + User_23Feb09.USER_GENDER + "=" + "'"
						+ gender + "'," + User_23Feb09.USER_ZIP + "=" + "'" + zip
						+ "'," + User_23Feb09.USER_FN + "=" + "'" + fn + "',"
						+ User_23Feb09.USER_LN + "=" + "'" + ln + "',"
						+ User_23Feb09.USER_EMAIL + "=" + "'" + email + "',"
						+ User_23Feb09.USER_CITY + "=" + "'" + city + "',"
						+ User_23Feb09.USER_STATE + "=" + "'" + state + "',"
						+ User_23Feb09.USER_COUNTRY + "=" + "'" + country + "',"
						+ User_23Feb09.USER_ADDRESS + "=" + "'" + address + "'";
				String whereClause = " where userId=" + user.getUserId();
				stmt = conn.createStatement();
				Log.info(updateStmt + value + whereClause);
				stmt.executeUpdate(updateStmt + value + whereClause);
				stmt.executeUpdate("update userauth set password='"
						+ registrationForm.getPassword() + "' where userid="
						+ user.getUserId());
				stmt.close();
				user = new LoginAction().populateUserInfo(conn, user
						.getUserId(), registrationForm.getPassword());
				session.setAttribute(PortalConstants.USER, user);
				return mapping.findForward("portal");
			} catch (Exception e) {
				Log.error(e.getMessage());
				return mapping.findForward("failure");
			}

		} else if (action.equals("Create")) {
			session.removeAttribute("USER_EXIST");
			return mapping.findForward("failure");
		}else if (action.equals("ViewInfo"))
		{
			//User user = (User)session.getAttribute("USER"); Modified by Arun 16MAY 2009
			User_23Feb09 user = (User_23Feb09)session.getAttribute("USER"); 
			String btDay = user.getBday();
			if (btDay.length()>7)
			{
				String bYear = btDay.substring(0,4);
				String bMonth = btDay.substring(5,7);
				String bDate = btDay.substring(8);
				registrationForm.setBirthdayYear(bYear);
				registrationForm.setBirthdayMonth(bMonth);
				registrationForm.setBirthDayDate(bDate.trim());
				
			}
			
			return mapping.findForward("failure");
		}

		return mapping.findForward("login");
	}

}